<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getComboDataApi, createShareDIYLink, getShareDIYLink } from "@/api/combo-h5"
import { type IGetComboData } from "@/api/combo/types/combo"
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, RefreshRight, CirclePlus } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { useUserStore } from "@/store/modules/user"
import useClipboard from "vue-clipboard3"
import vueQr from "vue-qr/src/packages/vue-qr.vue"
import { formatDateTime } from "@/utils"
import { useCommonStore } from "@/store/modules/common"
defineOptions({
  name: "ProductShare"
})
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const userStore = useUserStore()
const commonStore = useCommonStore()
//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive<any>({ data: {} })
//#endregion
//#region 查
const tableData = ref<IGetComboData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const dialogVisibleEwm = ref<boolean>(false)
const searchData = reactive({
  name: "",
  sku: "",
  superSku: "",
  status: "0"
  // team: userStore.teamName ? userStore.teamName : ""
})
const getTableData = () => {
  loading.value = true
  getComboDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name,
    teamId: userStore.usernameID,
    status: searchData.status
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}

//查看详情
const handleSeeInfo = (row: any) => {
  formData.data = row
  dialogVisible.value = true
}
const dialogVisible1 = ref<boolean>(false)
//查看大图
const seeZool = () => {
  dialogVisible1.value = true
}

//分享

/**分享产品 */
const dialogVisibleShare = ref<boolean>(false)
const link = ref<string>("")
const curObj = ref<any>(null)
const WEBURL = ref<any>(`${commonStore.BASEURL}/company`)
const webList = ref<any>([
  {
    key: commonStore.BASEURL,
    value: `${commonStore.BASEURL}/company`
  }
])

const handleShare = (row: any) => {
  dialogVisibleShare.value = true
  curObj.value = row
  link.value = `${WEBURL.value}/#/productDetil?p=${row.id}&u=${userStore.usernameID}&s=${row.systemId}&trackid=__TRACKID__`
  // link.value = `http://192.168.1.7:3336/#/productDetil?p=${row.id}&u=${userStore.usernameID}`
}
const changeUrl = () => {
  link.value = `${WEBURL.value}/#/productDetil?p=${curObj.value.id}&u=${userStore.usernameID}&s=${curObj.value.systemId}&trackid=__TRACKID__`
}
const { toClipboard } = useClipboard()
const copy = async (text: string) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制产品链接！")
  } catch (e) {
    console.error(e)
  }
}

//二维码弹窗，客服链接
import { createEwmPop, getEwmUrl } from "@/api/combo-h5"
import { uploadComboImageList } from "@/api/combo"
const formDataS = reactive<any>({
  ewmUrl: "",
  serviceLink: ""
})
// const ewmUrl = ref<string>("")
const creadEwm = () => {
  getEwmUrl({}).then((res: any) => {
    console.log(res)
    if (res.code == 200) {
      formDataS.ewmUrl = res.data.img
      formDataS.serviceLink = res.data.serviceLink
      fileList.value = res.data.img.split(",").map((item: any) => {
        return {
          url: `${commonStore.BASEURL}/image/${item}`
          // url: `http://192.168.0.152:8080/image/${item}`
        }
      })
    }
  })
  dialogVisibleEwm.value = true
}

const fileList = ref<any>([]) /**图片列表 */

const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList.value = []
  } else {
    fileList.value = resfileList
  }
}

// 预览图片
const dialogImageUrl = ref("") /**预览url  */
const dialogVisibleEwm1 = ref(false) /**预览弹窗 */
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisibleEwm1.value = true
}
// 移除图片
const handleRemove = (file: any) => {
  const list = fileList.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList.value = list
}

const handleCreate = async () => {
  if (fileList.value.length === 0) {
    ElMessage.error("请上图片")
    return
  }
  const fileData = new FormData()
  fileList.value.forEach((file: any) => {
    fileData.append("file", file.raw)
  })
  if (fileList.value[0].status === "ready") {
    await uploadComboImageList(fileData).then((res: any) => {
      if (res.code == 200) {
        formDataS.ewmUrl = res.data.split("/image/")[1]
        fileList.value = []
      }
    })
  }

  createEwmPop({ img: formDataS.ewmUrl, serviceLink: formDataS.serviceLink }).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success("上传成功")
      dialogVisibleEwm.value = false
    }
  })
}
//生成自定义新连接
const DIY = ref("")
const handleCreateLink = () => {
  if (DIY.value) {
    ElMessageBox.confirm(
      `确定生成:${WEBURL.value}/#/productDetil?p=${curObj.value.id}&u=${userStore.usernameID}&s=${curObj.value.systemId}&trackid=__TRACKID__&d=${DIY.value}`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(() => {
      link.value = `${WEBURL.value}/#/productDetil?p=${curObj.value.id}&u=${userStore.usernameID}&s=${curObj.value.systemId}&trackid=__TRACKID__&d=${DIY.value}`
      DIY.value = ""
      //新增一条历史记录接口
      createShareDIYLink({
        packageId: curObj.value.id,
        diyUrl: link.value
      }).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success(res.message)
          historyLink()
        }
      })
    })
  }
}
//分享链接历史记录
const dialogVisible2 = ref<boolean>(false)
const tableUrlLogs = ref<any>([])
const checkLog = () => {
  dialogVisible2.value = true
  historyLink()
}
const historyLink = () => {
  getShareDIYLink({ packageId: curObj.value.id }).then((res: any) => {
    if (res.code == 200) {
      tableUrlLogs.value = res.data.list
    }
  })
}
/**END */
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/**监听套餐缓存(pinia) */
import { useComboStore } from "@/store/modules/combo"
const comboStore = useComboStore()
comboStore.getComoboFn()
const comboList = ref<any>([])
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**department END */
// console.log(departTeam.value)
//合集套餐
import { getCompailationDataApi } from "@/api/combo"
const comboHJList = ref<any>([])
const getComboHjList = () => {
  getCompailationDataApi({
    page: 1,
    size: 1000,
    team: userStore.teamName
  })
    .then((res: any) => {
      comboHJList.value = res.data.list
    })
    .catch(() => {
      comboHJList.value = []
    })
}
getComboHjList()
const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList.value.filter((item: any) => {
    if (item.id == row.systemId) {
      celValue = item.name
    }
  })
  return celValue
}
const formatterCombo1 = (row: any, column: any, celValue: any) => {
  comboHJList.value.filter((item: any) => {
    if (item.id == row.heId) {
      celValue = item.name
    }
  })
  return celValue
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="套餐名">
          <el-input v-model.trim="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="creadEwm">H5其它相关配置</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column prop="id" label="ID" width="60" align="center" />
          <el-table-column prop="teamName" width="150" label="团队名" align="center" />
          <el-table-column prop="photo" label="是否上传身份证" align="center" width="160">
            <template #default="scope">
              <span v-if="scope.row.photo"> 是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column prop="isChange" label="是否选号" align="center" width="160">
            <template #default="scope">
              <span v-if="scope.row.isChange"> 是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="套餐名" align="center" />
          <el-table-column prop="anotherName" label="套餐内部名" align="center" />
          <el-table-column label="系统对应套餐" align="center" width="320">
            <template #default="scope">
              <span v-if="scope.row.systemId">{{ formatterCombo(scope.row, "", "") }}</span>
              <span v-else>{{ formatterCombo1(scope.row, "", "") }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="280" align="center">
            <template #default="scope">
              <el-button style="display: none" type="primary" text bg size="small" @click="handleSeeInfo(scope.row)"
                >查看详情</el-button
              >
              <el-button type="success" text bg size="small" @click="handleShare(scope.row)">分享产品</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!--查看详情 -->
    <el-dialog v-model="dialogVisible" title="查看详情" width="80%">
      <el-form ref="formRef" :model="formData.data" label-width="100px" label-position="left">
        <el-form-item prop="name" label="套餐名">
          <el-input v-model="formData.data.name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="systemId" label="系统对应套餐">
          <el-select v-model="formData.data.systemId" disabled style="width: 100%">
            <el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="image" label="H5背景图">
          <el-image
            @click="seeZool"
            style="width: 200px; height: 200px; cursor: pointer"
            :src="`${commonStore.BASEURL}/image/${formData.data.image}`"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1" @close="dialogVisible1 = false">
      <img w-full :src="`${commonStore.BASEURL}/image/${formData.data.image}`" alt="Preview Image" />
    </el-dialog>

    <el-dialog v-model="dialogVisibleShare" title="分享产品" width="50%">
      <div style="margin-bottom: 30px">
        <span style="margin-right: 26px">切换域名:</span>
        <el-select v-model="WEBURL" style="width: 80%" @change="changeUrl">
          <el-option v-for="item in webList" :key="item.value" :label="item.key" :value="item.value" />
        </el-select>
      </div>
      <div>
        <span>自定义内容：</span>
        <el-input
          v-model="DIY"
          placeholder="建议输入非中文字符，含中文字符可能会导致B站平台苹果用户打不开链接的情况"
          style="width: 70%; margin-right: 10px"
        />
        <el-button :disabled="!DIY" type="primary" @click="handleCreateLink">生成新连接</el-button>
      </div>
      <div style="margin: 30px 0">
        <span>产品链接：</span>
        <el-link>{{ link }}</el-link>
        <el-link type="primary" style="margin-left: 10px" @click="copy(link)"
          ><el-icon><DocumentCopy /></el-icon>复制</el-link
        >
      </div>
      <div>
        <span>产品链接历史记录：</span>
        <el-button type="primary" @click="checkLog">查看记录</el-button>
      </div>
      <div style="margin-top: 30px">
        <span style="vertical-align: top">产品二维码：</span>
        <vue-qr :text="link" :size="200" />
      </div>
    </el-dialog>
    <el-dialog v-model="dialogVisibleEwm" @close="dialogVisibleEwm = false">
      <el-form ref="formRef" :model="formDataS" label-width="100px" label-position="left">
        <el-form-item prop="serviceLink" label="客服链接">
          <el-input v-model="formDataS.serviceLink" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="img" label="二维码弹窗">
          <!-- <el-input v-model="formData.image" placeholder="请输入" />
           -->
          <el-upload
            :auto-upload="false"
            :file-list="fileList"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg"
            :disabled="fileList.length != 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisibleEwm = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisibleEwm1">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <el-dialog v-model="dialogVisible2">
      <el-table :data="tableUrlLogs">
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="diyUrl" label="链接地址" align="center" />
        <el-table-column prop="createBy" label="创建人" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.ageInput :deep(.el-input) {
  width: 20% !important;
}
:deep(.el-form-item__label) {
  width: 130px !important;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
:deep(.el-cascader) {
  width: 567px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
